package com.example.qqHook

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import de.robv.android.xposed.IXposedHookLoadPackage
import de.robv.android.xposed.callbacks.XC_LoadPackage
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedHelpers

class QQAutoLogin : IXposedHookLoadPackage {
    override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) {
        if (lpparam.packageName != "com.tencent.mobileqq") {
            return
        }

        XposedHelpers.findAndHookMethod(Application::class.java, "attach", Context::class.java, object : XC_MethodHook() {
            override fun afterHookedMethod(param: MethodHookParam) {
                val cl = (param.thisObject as Context).classLoader
                XposedHelpers.findAndHookMethod("com.tencent.mobileqq.activity.LoginActivity", cl, "onCreate", Bundle::class.java, object : XC_MethodHook() {
                    override fun afterHookedMethod(param: MethodHookParam) {
                        // 由于我们需要在Activity创建之后再弹出Toast，所以我们Hook方法执行之后
                        Toast.makeText(param.thisObject as Context, "模块加载成功！", Toast.LENGTH_SHORT).show()

                        val context = param.thisObject as Context
                        // 获取目标应用的 Context
                        val targetAppContext = context.createPackageContext("com.example.readfile", Context.CONTEXT_IGNORE_SECURITY or Context.CONTEXT_INCLUDE_CODE)

                        // 读取 SharedPreferences
                        val sharedPreferences: SharedPreferences = targetAppContext.getSharedPreferences("com.example.readfile", Context.MODE_PRIVATE)
                        val account = sharedPreferences.getString("account", "")
                        val password = sharedPreferences.getString("password", "")

                        val loginActivity = param.thisObject
                        val accountEditText = XposedHelpers.getObjectField(loginActivity, "accountEditText") as EditText
                        val passwordEditText = XposedHelpers.getObjectField(loginActivity, "passwordEditText") as EditText
                        val loginButton = XposedHelpers.getObjectField(loginActivity, "loginButton") as Button

                        accountEditText.setText(account)
                        passwordEditText.setText(password)
                        loginButton.performClick()
                    }
                })
            }
        })
    }
}
